package Streamer;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Observable;

import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class TCPClient extends Observable implements Runnable
{
	private Socket clientSocket;
	private BufferedReader inFromServer;
	private DataOutputStream outToServer;
	private String serverAddress;
	private int serverPort;
	private int grantedPort;
	public UDPClient udpClient;
	private boolean connected = false;
	

	public TCPClient(String serverAddress, int serverPort) throws UnknownHostException, IOException 
	{
		this.serverAddress = serverAddress;
		this.serverPort = serverPort;
		this.clientSocket = new Socket(serverAddress, this.serverPort);
		this.inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
		connected = true;
	}
	
	public int getGrantedPort()
	{
		return grantedPort;
	}
	
	public void run()
	{
		String serverResponse = "";
		
		try
		{
			read(); // Welcome
			write("Create\n");
			read(); // Start\n
			serverResponse = read(); // Port 

			grantedPort = Integer.parseInt(serverResponse);	
			udpClient = new UDPClient(serverAddress, getGrantedPort());	
			write("Start\n");
			udpClient.start();	
			
			
			// Keep alive
			while(connected)
			{
				Thread.sleep(1000L);
				if (connected)
					write("Alive\n");
			}
		}
		
		catch(IOException e)
		{
			connected = false;
			setChanged();
			notifyObservers("Forbindelses mistet");
		}
		
		catch(Exception e)
		{
			connected = false;
			setChanged();
			notifyObservers("Exception: " + e.getMessage());
		}
	}
	
	private String read()
	{
		try 
		{
			return inFromServer.readLine();
		} 
		
		catch (IOException e) 
		{
			setChanged();
			notifyObservers(e.getMessage());
		}
		
		return "";
	}
	
	public void write(String text) throws IOException
	{
			outToServer = new DataOutputStream(clientSocket.getOutputStream());
			outToServer.writeBytes(text);
	}

	public void StopAll() 
	{
		udpClient.stopThread();
		connected = false;
		
		try 
		{
			clientSocket.close();
		} 
		
		catch (IOException e) 
		{
			setChanged();
			notifyObservers(e.getMessage());
		}
	}
}